package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl  implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    //保存排班
    @Override
    public void save(Map<String, Object> paramMap) {
        //1把map转化成Department
        //把map转化json串
        String schJsonStr = JSONObject.toJSONString(paramMap);
        //把json串转化成对象
        Schedule schedule = JSONObject.parseObject(schJsonStr, Schedule.class);
        //2根据医院编码，排班编码（医院自己的编码）查询排班信息
        Schedule scheduleExist =
                scheduleRepository.getByHoscodeAndHosScheduleId(
                        schedule.getHoscode(),schedule.getHosScheduleId()
                );
        //3判断是更新，新增
        if(scheduleExist!=null){
            //更新
            schedule.setId(scheduleExist.getId());
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else{
            //新增
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }

    //查询排班规则汇总数据
    @Override
    public Map<String, Object> getScheduleRule(long page, long limit,
                                               String hoscode, String depcode) {
        //0创建返回对象
        Map<String, Object> result = new HashMap<>();
        //1根据查询条件，分页查询排班聚合数据（获取List）
        //1.1设置查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode);
        //1.2聚合统计（分组统计）
        Aggregation agg = Aggregation.newAggregation(
              //1.3设置筛选条件
                Aggregation.match(criteria),
                //1.4分组字段
                Aggregation.group("workDate")
                        //1.5分组统计结果
                .first("workDate").as("workDate")
                        //统计医生数量
                .count().as("docCount")
                        //统计号源信息
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //1.6排序
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                //1.7分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //1.8查询数据
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList =
                aggregate.getMappedResults();
        //2根据查询条件，查询排班聚合总数据量（total）
        Aggregation totalAgg = Aggregation.newAggregation(
                //2.1设置筛选条件
                Aggregation.match(criteria),
                //2.2分组字段
                Aggregation.group("workDate")
        );
        //2.3
        AggregationResults<BookingScheduleRuleVo> aggregateTotal =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleTotal =
                aggregateTotal.getMappedResults();
        int total = bookingScheduleRuleTotal.size();
        //3 借助工具算出周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        //4封装数据
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);
        //5数据补全
        //5.1查询医院名称
        String hosname = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosname);
        result.put("baseMap",baseMap);
        return result;
    }
    //查询排班详细数据集合
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        //1根据医院编码、科室编码、排班日期查询排班记录
        //转化workDate类型，String->Date
        Date workDateToDate = new DateTime(workDate).toDate();

        List<Schedule> scheduleList =
                scheduleRepository.getByHoscodeAndDepcodeAndWorkDate(
                        hoscode,depcode,workDateToDate
                );

        //2遍历集合根据编码查询具体名称封装进行展示
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });

        return scheduleList;
    }





    //获取可预约排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        //1根据hoscode查询医院信息，获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if(hospital==null){
            throw  new YyghException(20001,"医院信息有误");
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //2根据预约规则，查询带分页的可预约日期集合IPage<Date>
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);
        List<Date> dateList = iPage.getRecords();

        //3参考后台接口实现，完成排班规则聚合查询结果
        //3.1拼写筛选条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        //3.2创建聚合查询对象
        Aggregation agg = Aggregation.newAggregation(
                //设置筛选条件
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate")
                        //分组统计结果
                        .first("workDate").as("workDate")
                        //统计医生数量
                        .count().as("docCount")
                        //统计号源信息
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber")
        );
        //3.3使用mongoTemplate进行聚合查询
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList =
                aggregate.getMappedResults();
        //3.4 进行类型转化 scheduleVoList->map  k:workDate  v:BookingScheduleRuleVo
        Map<Date,BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)){
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(
                    BookingScheduleRuleVo::getWorkDate,
                    BookingScheduleRuleVo->BookingScheduleRuleVo
            ));
        }

        //4实现数据整合，（1）可预约日期集合dateList （2）排班规则聚合查询结果scheduleVoMap
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0,let=dateList.size(); i < let; i++) {
            //4.1取出dateList日期
            Date date = dateList.get(i);
            //4.2以date作为key，查询scheduleVoMap
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //4.3 如果bookingScheduleRuleVo为空，需要初始化
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //出诊医生数量为0
                bookingScheduleRuleVo.setDocCount(0);
                //设置剩余预约号数为不可预约（-1）
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //4.4设置周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //4.5 判断是否是最后一页，最后一条的记录，更改状态为即将放号
            // 状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i==let-1&&page==iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else{
                bookingScheduleRuleVo.setStatus(0);
            }
            //4.6 当天记录，如果已经过停止挂号时间，更改状态当天已停止挂号
            if(i==0&&page==1){
                DateTime stopTime = this.getDateTime(new Date(),bookingRule.getStopTime());
                if(stopTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //5把数据封装到map里，返回
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    //根据排班id获取排班详情
    @Override
    public Schedule findScheduleById(String id) {
        Schedule schedule = this.packageSchedule(scheduleRepository.findById(id).get());
        return schedule;
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //1获取排班信息
        Schedule schedule = this.findScheduleById(scheduleId);
        if (schedule==null){
            throw new YyghException(20001,"排班信息有误");
        }
        //2获取医院信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital==null){
            throw new YyghException(20001,"医院信心有误");
        }
        //3取出预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule==null){
            throw new YyghException(20001,"挂号规则有误");
        }

        //封装数据返回
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(hospital.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(
                departmentService.getDepName(hospital.getHoscode(),schedule.getDepcode()));

        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号时间,根据bookingRule计算
        // 退号截止天数（如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quiDate = new DateTime(schedule.getWorkDate()).plusDays(quitDay);
        String quitTime = bookingRule.getQuitTime();
        scheduleOrderVo.setQuitTime(this.getDateTime(quiDate.toDate(),quitTime).toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime()
                .plusDays(bookingRule.getCycle())
                .toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    //修改排班
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    ////根据hoscode、hosScheduleId查询排班信息
    @Override
    public Schedule getByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        return schedule;
    }


    //根据预约规则，查询带分页的可预约日期集合IPage<Data>
    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule){
        //1获取当天可以预约时间，日期+预约时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        //2获取预约周期
        Integer cycle = bookingRule.getCycle();
        if (releaseTime.isBeforeNow())cycle+=1;

        //3根据预约周期计算可预约日期集合
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime plusDays = new DateTime().plusDays(i);
            String dateString = plusDays.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }

        //4获取分页参数
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;
        if (end>dateList.size()) end = dateList.size();

        //5带分页的可预约日期集合
        List<Date> datePageList = new ArrayList<>();
        for (int i = start; i<end;i++){
            datePageList.add(dateList.get(i));
        }
        //6封装到分页对象
        IPage<Date> iPage=new Page<>(page,limit,dateList.size());
        iPage.setRecords(datePageList);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date,String timeString){
       String dateTimeString= new DateTime(date).toString("yyyy-MM-dd")+" "+timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    private Schedule packageSchedule(Schedule schedule){
        //设置医院名称
        schedule.getParam().put("hosname",
                hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
